using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Volo.Abp;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;
using Matrix.Notification.Domain.Shared.Notifications;

namespace Matrix.Notification.Domain.Notifications
{
    /// <summary>
    /// 通知模板聚合根实体
    /// </summary>
    public class NotificationTemplate : FullAuditedAggregateRoot<Guid>, IMultiTenant
    {
        /// <summary>
        /// 租户ID
        /// </summary>
        public virtual Guid? TenantId { get; protected set; }

        /// <summary>
        /// 模板名称
        /// </summary>
        public virtual string Name { get; protected set; } = string.Empty;

        /// <summary>
        /// 模板显示名称
        /// </summary>
        public virtual string DisplayName { get; protected set; } = string.Empty;

        /// <summary>
        /// 模板描述
        /// </summary>
        public virtual string? Description { get; protected set; }

        /// <summary>
        /// 模板类型
        /// </summary>
        public virtual TemplateType Type { get; protected set; }

        /// <summary>
        /// 通知类型
        /// </summary>
        public virtual NotificationType NotificationType { get; protected set; }

        /// <summary>
        /// 支持的通知渠道
        /// </summary>
        public virtual string SupportedChannels { get; protected set; } = string.Empty;

        /// <summary>
        /// 主题模板（用于邮件通知）
        /// </summary>
        public virtual string? SubjectTemplate { get; protected set; }

        /// <summary>
        /// 内容模板
        /// </summary>
        public virtual string ContentTemplate { get; protected set; } = string.Empty;

        /// <summary>
        /// HTML内容模板（可选）
        /// </summary>
        public virtual string? HtmlContentTemplate { get; protected set; }

        /// <summary>
        /// 模板参数定义（JSON格式）
        /// </summary>
        public virtual string? ParameterDefinitions { get; protected set; }

        /// <summary>
        /// 默认参数值（JSON格式）
        /// </summary>
        public virtual string? DefaultParameters { get; protected set; }

        /// <summary>
        /// 模板标签
        /// </summary>
        public virtual string Tags { get; protected set; } = string.Empty;

        /// <summary>
        /// 模板分类
        /// </summary>
        public virtual string? Category { get; protected set; }

        /// <summary>
        /// 是否启用
        /// </summary>
        public virtual bool IsEnabled { get; protected set; }

        /// <summary>
        /// 是否为系统模板
        /// </summary>
        public virtual bool IsSystem { get; protected set; }

        /// <summary>
        /// 是否支持多语言
        /// </summary>
        public virtual bool SupportsMultiLanguage { get; protected set; }

        /// <summary>
        /// 默认语言
        /// </summary>
        public virtual string DefaultLanguage { get; protected set; } = "zh-CN";

        /// <summary>
        /// 支持的语言列表（JSON格式）
        /// </summary>
        public virtual string? SupportedLanguages { get; protected set; }

        /// <summary>
        /// 模板版本
        /// </summary>
        public virtual string Version { get; protected set; } = "1.0.0";

        /// <summary>
        /// 上次使用时间
        /// </summary>
        public virtual DateTime? LastUsedTime { get; protected set; }

        /// <summary>
        /// 使用次数
        /// </summary>
        public virtual int UsageCount { get; protected set; }

        /// <summary>
        /// 模板评分
        /// </summary>
        public virtual double Rating { get; protected set; }

        /// <summary>
        /// 评分次数
        /// </summary>
        public virtual int RatingCount { get; protected set; }

        /// <summary>
        /// 优先级
        /// </summary>
        public virtual int Priority { get; protected set; }

        /// <summary>
        /// 模板编码
        /// </summary>
        public virtual string TemplateCode { get; protected set; } = string.Empty;

        /// <summary>
        /// 模板缩略图
        /// </summary>
        public virtual string? Thumbnail { get; protected set; }

        /// <summary>
        /// 模板预览数据（JSON格式）
        /// </summary>
        public virtual string? PreviewData { get; protected set; }

        /// <summary>
        /// 审核状态
        /// </summary>
        public virtual TemplateApprovalStatus ApprovalStatus { get; protected set; }

        /// <summary>
        /// 审核人ID
        /// </summary>
        public virtual Guid? ApprovedById { get; protected set; }

        /// <summary>
        /// 审核时间
        /// </summary>
        public virtual DateTime? ApprovedTime { get; protected set; }

        /// <summary>
        /// 审核意见
        /// </summary>
        public virtual string? ApprovalNotes { get; protected set; }

        /// <summary>
        /// 父模板ID（用于模板继承）
        /// </summary>
        public virtual Guid? ParentTemplateId { get; protected set; }

        /// <summary>
        /// 模板元数据（JSON格式）
        /// </summary>
        public virtual string? Metadata { get; protected set; }

        /// <summary>
        /// 模板设置（JSON格式）
        /// </summary>
        public virtual string? Settings { get; protected set; }

        protected NotificationTemplate()
        {
        }

        /// <summary>
        /// 创建新模板
        /// </summary>
        public NotificationTemplate(
            Guid id,
            Guid? tenantId,
            string name,
            string displayName,
            TemplateType type,
            NotificationType notificationType,
            string contentTemplate,
            string? description = null,
            string? subjectTemplate = null,
            string? htmlContentTemplate = null)
            : base(id)
        {
            TenantId = tenantId;
            Name = Check.NotNullOrWhiteSpace(name, nameof(name), maxLength: 100);
            DisplayName = Check.NotNullOrWhiteSpace(displayName, nameof(displayName), maxLength: 200);
            Type = type;
            NotificationType = notificationType;
            ContentTemplate = Check.NotNullOrWhiteSpace(contentTemplate, nameof(contentTemplate));
            Description = description;
            SubjectTemplate = subjectTemplate;
            HtmlContentTemplate = htmlContentTemplate;
            IsEnabled = true;
            IsSystem = false;
            SupportsMultiLanguage = false;
            DefaultLanguage = "zh-CN";
            Version = "1.0.0";
            UsageCount = 0;
            Rating = 0;
            RatingCount = 0;
            Priority = 0;
            ApprovalStatus = TemplateApprovalStatus.Pending;
            TemplateCode = GenerateTemplateCode();
        }

        /// <summary>
        /// 更新基本信息
        /// </summary>
        public virtual NotificationTemplate UpdateInfo(
            string displayName,
            string? description = null,
            string? category = null,
            string? tags = null)
        {
            DisplayName = Check.NotNullOrWhiteSpace(displayName, nameof(displayName), maxLength: 200);
            Description = description;
            Category = category;
            Tags = tags ?? string.Empty;
            return this;
        }

        /// <summary>
        /// 更新模板内容
        /// </summary>
        public virtual NotificationTemplate UpdateContent(
            string contentTemplate,
            string? subjectTemplate = null,
            string? htmlContentTemplate = null)
        {
            ContentTemplate = Check.NotNullOrWhiteSpace(contentTemplate, nameof(contentTemplate));
            SubjectTemplate = subjectTemplate;
            HtmlContentTemplate = htmlContentTemplate;
            Version = IncrementVersion();
            return this;
        }

        /// <summary>
        /// 设置支持的通知渠道
        /// </summary>
        public virtual NotificationTemplate SetSupportedChannels(params NotificationChannel[] channels)
        {
            if (channels == null || channels.Length == 0)
            {
                throw new ArgumentException("至少需要指定一个通知渠道", nameof(channels));
            }

            var channelList = new List<string>();
            foreach (var channel in channels)
            {
                channelList.Add(channel.ToString());
            }

            SupportedChannels = string.Join(",", channelList);
            return this;
        }

        /// <summary>
        /// 添加通知渠道支持
        /// </summary>
        public virtual NotificationTemplate AddSupportedChannel(NotificationChannel channel)
        {
            var channels = GetSupportedChannels();
            if (!channels.Contains(channel))
            {
                channels.Add(channel);
                var channelList = channels.Select(c => c.ToString());
                SupportedChannels = string.Join(",", channelList);
            }
            return this;
        }

        /// <summary>
        /// 移除通知渠道支持
        /// </summary>
        public virtual NotificationTemplate RemoveSupportedChannel(NotificationChannel channel)
        {
            var channels = GetSupportedChannels();
            if (channels.Contains(channel))
            {
                channels.Remove(channel);
                var channelList = channels.Select(c => c.ToString());
                SupportedChannels = string.Join(",", channelList);
            }
            return this;
        }

        /// <summary>
        /// 获取支持的通知渠道
        /// </summary>
        public virtual List<NotificationChannel> GetSupportedChannels()
        {
            var channels = new List<NotificationChannel>();
            if (!string.IsNullOrEmpty(SupportedChannels))
            {
                var channelStrings = SupportedChannels.Split(',');
                foreach (var channelString in channelStrings)
                {
                    if (Enum.TryParse<NotificationChannel>(channelString.Trim(), out var channel))
                    {
                        channels.Add(channel);
                    }
                }
            }
            return channels;
        }

        /// <summary>
        /// 检查是否支持指定渠道
        /// </summary>
        public virtual bool SupportsChannel(NotificationChannel channel)
        {
            return GetSupportedChannels().Contains(channel);
        }

        /// <summary>
        /// 设置参数定义
        /// </summary>
        public virtual NotificationTemplate SetParameterDefinitions(string parameterDefinitions)
        {
            ParameterDefinitions = parameterDefinitions;
            return this;
        }

        /// <summary>
        /// 设置默认参数
        /// </summary>
        public virtual NotificationTemplate SetDefaultParameters(string defaultParameters)
        {
            DefaultParameters = defaultParameters;
            return this;
        }

        /// <summary>
        /// 启用模板
        /// </summary>
        public virtual NotificationTemplate Enable()
        {
            IsEnabled = true;
            return this;
        }

        /// <summary>
        /// 禁用模板
        /// </summary>
        public virtual NotificationTemplate Disable()
        {
            IsEnabled = false;
            return this;
        }

        /// <summary>
        /// 启用多语言支持
        /// </summary>
        public virtual NotificationTemplate EnableMultiLanguage(string defaultLanguage = "zh-CN")
        {
            SupportsMultiLanguage = true;
            DefaultLanguage = defaultLanguage;
            return this;
        }

        /// <summary>
        /// 禁用多语言支持
        /// </summary>
        public virtual NotificationTemplate DisableMultiLanguage()
        {
            SupportsMultiLanguage = false;
            return this;
        }

        /// <summary>
        /// 设置支持的语言
        /// </summary>
        public virtual NotificationTemplate SetSupportedLanguages(params string[] languages)
        {
            if (languages == null || languages.Length == 0)
            {
                throw new ArgumentException("至少需要指定一种语言", nameof(languages));
            }

            SupportedLanguages = string.Join(",", languages);
            return this;
        }

        /// <summary>
        /// 获取支持的语言列表
        /// </summary>
        public virtual List<string> GetSupportedLanguages()
        {
            var languages = new List<string>();
            if (!string.IsNullOrEmpty(SupportedLanguages))
            {
                languages.AddRange(SupportedLanguages.Split(',').Select(l => l.Trim()));
            }
            return languages;
        }

        /// <summary>
        /// 标记为系统模板
        /// </summary>
        public virtual NotificationTemplate MarkAsSystem()
        {
            IsSystem = true;
            return this;
        }

        /// <summary>
        /// 标记为自定义模板
        /// </summary>
        public virtual NotificationTemplate MarkAsCustom()
        {
            IsSystem = false;
            return this;
        }

        /// <summary>
        /// 记录使用
        /// </summary>
        public virtual NotificationTemplate RecordUsage()
        {
            LastUsedTime = DateTime.UtcNow;
            UsageCount++;
            return this;
        }

        /// <summary>
        /// 设置评分
        /// </summary>
        public virtual NotificationTemplate SetRating(double rating)
        {
            if (rating < 0 || rating > 5)
            {
                throw new ArgumentException("评分必须在0-5之间", nameof(rating));
            }

            // 计算新的平均评分
            var totalScore = Rating * RatingCount + rating;
            RatingCount++;
            Rating = totalScore / RatingCount;
            return this;
        }

        /// <summary>
        /// 设置优先级
        /// </summary>
        public virtual NotificationTemplate SetPriority(int priority)
        {
            if (priority < 0 || priority > 100)
            {
                throw new ArgumentException("优先级必须在0-100之间", nameof(priority));
            }

            Priority = priority;
            return this;
        }

        /// <summary>
        /// 设置缩略图
        /// </summary>
        public virtual NotificationTemplate SetThumbnail(string thumbnail)
        {
            Thumbnail = thumbnail;
            return this;
        }

        /// <summary>
        /// 设置预览数据
        /// </summary>
        public virtual NotificationTemplate SetPreviewData(string previewData)
        {
            PreviewData = previewData;
            return this;
        }

        /// <summary>
        /// 提交审核
        /// </summary>
        public virtual NotificationTemplate SubmitForApproval()
        {
            if (IsSystem)
            {
                throw new UserFriendlyException("系统模板无需审核");
            }

            ApprovalStatus = TemplateApprovalStatus.Pending;
            return this;
        }

        /// <summary>
        /// 审核通过
        /// </summary>
        public virtual NotificationTemplate Approve(Guid approvedById, string? approvalNotes = null)
        {
            ApprovalStatus = TemplateApprovalStatus.Approved;
            ApprovedById = approvedById;
            ApprovedTime = DateTime.UtcNow;
            ApprovalNotes = approvalNotes;
            return this;
        }

        /// <summary>
        /// 审核拒绝
        /// </summary>
        public virtual NotificationTemplate Reject(Guid approvedById, string approvalNotes)
        {
            ApprovalStatus = TemplateApprovalStatus.Rejected;
            ApprovedById = approvedById;
            ApprovedTime = DateTime.UtcNow;
            ApprovalNotes = Check.NotNullOrWhiteSpace(approvalNotes, nameof(approvalNotes));
            return this;
        }

        /// <summary>
        /// 设置父模板
        /// </summary>
        public virtual NotificationTemplate SetParentTemplate(Guid? parentTemplateId)
        {
            ParentTemplateId = parentTemplateId;
            return this;
        }

        /// <summary>
        /// 设置元数据
        /// </summary>
        public virtual NotificationTemplate SetMetadata(string metadata)
        {
            Metadata = metadata;
            return this;
        }

        /// <summary>
        /// 设置模板设置
        /// </summary>
        public virtual NotificationTemplate SetSettings(string settings)
        {
            Settings = settings;
            return this;
        }

        /// <summary>
        /// 克隆模板
        /// </summary>
        public virtual NotificationTemplate Clone(string newName, string newDisplayName)
        {
            return new NotificationTemplate(
                Guid.NewGuid(),
                TenantId,
                newName,
                newDisplayName,
                Type,
                NotificationType,
                ContentTemplate,
                Description,
                SubjectTemplate,
                HtmlContentTemplate)
            {
                IsSystem = false,
                IsEnabled = true,
                SupportsMultiLanguage = SupportsMultiLanguage,
                DefaultLanguage = DefaultLanguage,
                SupportedLanguages = SupportedLanguages,
                Priority = Priority,
                Category = Category,
                Tags = Tags,
                ParameterDefinitions = ParameterDefinitions,
                DefaultParameters = DefaultParameters,
                Thumbnail = Thumbnail,
                PreviewData = PreviewData,
                ParentTemplateId = Id,
                Metadata = Metadata,
                Settings = Settings
            };
        }

        /// <summary>
        /// 生成模板编码
        /// </summary>
        protected virtual string GenerateTemplateCode()
        {
            return $"TPL_{DateTime.UtcNow:yyyyMMdd}_{Guid.NewGuid().ToString("N")[..8].ToUpper()}";
        }

        /// <summary>
        /// 递增版本号
        /// </summary>
        protected virtual string IncrementVersion()
        {
            try
            {
                var version = new Version(Version);
                var newVersion = new Version(version.Major, version.Minor, version.Build + 1);
                return newVersion.ToString();
            }
            catch
            {
                return Version + ".1";
            }
        }
    }

    /// <summary>
    /// 模板审核状态枚举
    /// </summary>
    public enum TemplateApprovalStatus
    {
        /// <summary>
        /// 待审核
        /// </summary>
        Pending = 0,

        /// <summary>
        /// 审核通过
        /// </summary>
        Approved = 1,

        /// <summary>
        /// 审核拒绝
        /// </summary>
        Rejected = 2,

        /// <summary>
        /// 无需审核
        /// </summary>
        NotRequired = 3
    }
}